<?php
/**
 * Created by PhpStorm.
 * User: zhang
 * Date: 2018/5/6
 * Time: 19:00
 */

namespace app\account\controller;

use app\account\model\User;

class Recommend extends User{

    /**
     *
     * @api {get} /account/recommend 推荐人
     * @apiDescription 推荐人
     * @apiName 123
     * @apiGroup account
     * @apiParam {string} uid 用户的id
     * @apiParam {string} subuid 下级uid
     *
     *@apiParamExample {json} Request-Example:
     *     {
     *       "uid": rUGnbBqkfRZR，
     *       "subuid": sWrUQjNXvqZi
     *     }
     *
     * @apiSuccess {String} code 0 表示失败 1 表示成功.
     * @apiSuccess {String} msg 登录的个人信息.
     * @apiSuccessExample {json} Success-Response:
     *     {
     *       "code": "1",
     *       "msg": "xxx"
     *     }
     */
    public function index(){
        $uid = $_GET['uid'];
        $subuid = $_GET['subuid'];
        if(empty($uid)||empty($subuid)){
            echo echoJson(0, "数据不能为空！");
        }
        if($uid==$subuid){
            echo echoJson(0, "自己不能推荐自己！");
        }
        if(!$this->getRecommand($subuid)){
            $this->bindUser($uid,$subuid);
            echo echoJson(1, "添加成功");
        }else{
            echo echoJson(0, "用户已经有上级");
        }
    }

    //返回推荐者
    public function recommend(){
        $uid = $_GET["uid"];

        echo echoJson(1,$this->getRecommand($uid));
    }

    //被推荐
    public function recommended(){
        $uid = $_GET["uid"];

        echoJson(1,$this->getRecommanded($uid));
    }

    function getRecommanded($uid){
        $sql = "select subordinate_id from agency_user_subordinate where uid='$uid'";

        $result = $this->mysql->selectSQLAll($sql);
        $i=0;
        foreach ($result as $a){

            $result=$this->getUserName($a[0]);
            $arr[$i] = $result;
            $i++;
        }

        return ($arr);

    }

    function getRecommand($subuid){
        $sql = "select uid from agency_user_subordinate where subordinate_id='$subuid'";
        $result = $this->mysql->selectSQLRow($sql);

        if($result){
            //echo echoJson(0, "用户已经有上级");
            $result=$this->getUserName($result["uid"]);
            return $result;
        }

        return false;
    }

    function bindUser($uid,$subuid){
        $sql = "insert into agency_user_subordinate(uid,subordinate_id) values ('$uid','$subuid')";
        $this->mysql->insertSQL($sql);
    }
}
